from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

from app.core.config import settings

# 根据连接字符串创建异步引擎
# 将SQLite的同步URL转换为异步URL
if settings.DATABASE_URL.startswith("sqlite"):
    async_database_url = settings.DATABASE_URL.replace("sqlite", "sqlite+aiosqlite", 1)
else:
    async_database_url = settings.DATABASE_URL

engine = create_async_engine(
    async_database_url,
    pool_pre_ping=True,
    echo=True,  # 在开发期间启用SQL语句日志
)

# 同步引擎用于Alembic迁移
sync_engine = create_engine(
    settings.DATABASE_URL,
    pool_pre_ping=True,
)

# 创建会话工厂
SessionLocal = sessionmaker(
    autocommit=False,
    autoflush=False,
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,
)


async def get_db() -> AsyncSession:
    """
    依赖项，用于获取数据库会话
    """
    async with SessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()